
package com.netease.xone.fragment;

import java.util.ArrayList;
import java.util.List;

import net.simonvt.numberpicker.NumberPicker;
import net.simonvt.numberpicker.NumberPicker.OnValueChangeListener;
import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import protocol.meta.FilterInfo;
import protocol.meta.GameFilterSubject;
import protocol.meta.Subject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.handmark.pulltorefresh.library.X1LoadingAdapterViewBase.OnLoadingListener;
import com.netease.framework.widget.LinkedListAdapter;
import com.netease.pkgRelated.XoneConsts;
import com.netease.pkgRelated.XoneConsts.MENU_ID;
import com.netease.xone.R;
import com.netease.xone.dataMgr.CityManager;
import com.netease.xone.view.SettingItemView;
import com.netease.xone.widget.listview.LoadingListView;

public class FragmentModifyFindCondition extends FragmentBase {

    public static FragmentModifyFindCondition newInstance(FilterInfo filter) {
        FragmentModifyFindCondition f = new FragmentModifyFindCondition();
        Bundle b = new Bundle();
        b.putParcelable(XoneConsts.BUNDLE_KEY.FIND_FRIENDS_FILTER, filter);
        f.setArguments(b);
        return f;
    }

    // View
    private LoadingListView mLoadingList;
    private SettingItemView mGenderItem;
    private SettingItemView mCityItem;
    private SettingItemView mAuthItem;// 认证
    private CheckBox mGameFilterSwitch;
    private TextView mGameFilterHint;
    // dialog city
    private NumberPicker mProvincePicker;
    private NumberPicker mCityPicker;
    private Dialog mSelectCityDialog;
    private CityManager mCityManager;
    // dialog gender
    private AlertDialog mSelectGenderDialog;
    // dialog auth
    private AlertDialog mSelectAuthDialog;
    // data
    private GameFilterAdapter mAdapter;
    private FilterInfo mFilter;
    private List<GameFilterSubject> mGameFilterList;
    // Tid
    private int mTid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setTitle(R.string.sift);
        mFilter = getArguments().getParcelable(XoneConsts.BUNDLE_KEY.FIND_FRIENDS_FILTER);
        setHasOptionsMenu(true);
        XoneService.getInstance().addListener(mCallBack);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.add(0, MENU_ID.menu_modify_filter_confirm, 0, "")
                .setIcon(R.drawable.icon_action_done_selector)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_ID.menu_modify_filter_confirm:
                mFilter.subjectIdList.clear();
                if(mFilter.gameFilter){
                    for(GameFilterSubject filter : mGameFilterList){
                        if(filter.selected){
                            mFilter.subjectIdList.add(filter.subject.subjectName);
                        }
                    }
                }
                Intent i = new Intent();
                i.putExtra(XoneConsts.BUNDLE_KEY.FIND_FRIENDS_FILTER, mFilter);
                getActivity().setResult(Activity.RESULT_OK, i);
                getActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_loading_listview, null);

        mLoadingList = (LoadingListView)view.findViewById(R.id.loading_list);
        mLoadingList.disablePullToRefresh();
        mAdapter = new GameFilterAdapter(getActivity());
        mLoadingList.setOnLoadingListener(new OnLoadingListener() {

            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoading() {
                mTid = XoneService.getInstance()
                        .doGetSubjectList(XoneConsts.SUBJECT_LIST_TYPE.GAME);
            }

            @Override
            public void onLoadingMore() {

            }
        });
        mLoadingList.setAdapter(mAdapter);

        View header = inflater.inflate(R.layout.view_modify_search_header, null);
        mGenderItem = (SettingItemView)header.findViewById(R.id.modify_filter_item_gender);
        mCityItem = (SettingItemView)header.findViewById(R.id.modify_filter_item_city);
        mAuthItem = (SettingItemView)header.findViewById(R.id.modify_filter_item_auth);
        mGenderItem.setOnClickListener(mClick);
        mCityItem.setOnClickListener(mClick);
        mAuthItem.setOnClickListener(mClick);

        mGameFilterSwitch = (CheckBox)header.findViewById(R.id.modify_filter_item_game_switch);
        mGameFilterHint = (TextView)header.findViewById(R.id.modify_filter_item_game_hint);
        mGameFilterSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mFilter.gameFilter = isChecked;
                if (isChecked) {
                    if(mGameFilterList == null || mGameFilterList.size() != 0){
                        mLoadingList.reLoad();
                    }else{
                        mAdapter.addTail(mGameFilterList);
                    }
                    mGameFilterHint.setVisibility(View.VISIBLE);
                } else {
                    mAdapter.clear();
                    mGameFilterHint.setVisibility(View.GONE);
                }
            }
        });

        mGenderItem.setTitleText(getString(R.string.gender));
        mCityItem.setTitleText(getString(R.string.city));
        mAuthItem.setTitleText(getString(R.string.weather_authentication));
        updateDesc();

        mLoadingList.getRefreshableView().addHeaderView(header);
        return view;
    }

    private void updateDesc() {
        switch (mFilter.gender) {
            case -1:
                mGenderItem.setDesText(getString(R.string.filter_condition_unlimited));
                break;
            case 1:
                mGenderItem.setDesText(getString(R.string.male));
                break;
            case 2:
                mGenderItem.setDesText(getString(R.string.female));
                break;
        }
        StringBuilder location = new StringBuilder();
        if (!TextUtils.isEmpty(mFilter.province)
                && !mFilter.province.equals(getString(R.string.filter_condition_unlimited))) {
            location.append(mFilter.province).append(" ");
        }
        if (!TextUtils.isEmpty(mFilter.city)
                && !mFilter.city.equals(getString(R.string.filter_condition_unlimited))) {
            location.append(mFilter.city);
        }
        if (!TextUtils.isEmpty(location.toString())) {
            mCityItem.setDesText(location.toString());
        } else {
            mCityItem.setDesText(getString(R.string.filter_condition_unlimited));
        }
        switch (mFilter.userType) {
            case 0:
                mAuthItem.setDesText(getString(R.string.no));
                break;
            case 1:
                mAuthItem.setDesText(getString(R.string.yes));
                break;
            case -1:
                mAuthItem.setDesText(getString(R.string.filter_condition_unlimited));
                break;
        }
        mGameFilterSwitch.setChecked(mFilter.gameFilter);
    }

    private OnClickListener mClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v == mGenderItem) {
                showSelectGender();
            } else if (v == mCityItem) {
                showSelectCity();
            } else if (v == mAuthItem) {
                showSelectAuth();
            }
        }
    };

    private void showSelectCity() {
        if (mSelectCityDialog == null) {
            mCityManager = new CityManager(getActivity(), true);
            final String[] provinceArray = mCityManager.getProvinces();
            View pickerView = View.inflate(getActivity(), R.layout.view_city_picker, null);
            mProvincePicker = (NumberPicker)pickerView.findViewById(R.id.province_picker);
            mCityPicker = (NumberPicker)pickerView.findViewById(R.id.city_picker);
            mProvincePicker.setMinValue(0);
            mProvincePicker.setMaxValue(provinceArray.length - 1);
            mProvincePicker.setDisplayedValues(provinceArray);
            int provinceIndex = mCityManager.getProvinceIndex(mFilter.province);
            if (provinceIndex >= 0) {
                mProvincePicker.setValue(provinceIndex);
            }
            String[] cityArray = null;
            if (provinceIndex > 0) {
                cityArray = mCityManager.getCity(provinceArray[provinceIndex]);
            }
            if (cityArray != null) {
                mCityPicker.setVisibility(View.VISIBLE);
                mCityPicker.setMaxValue(cityArray.length - 1);
                mCityPicker.setMinValue(0);
                mCityPicker.setDisplayedValues(cityArray);
                int cityIndex = mCityManager.getCityIndex(mFilter.province, mFilter.city);
                if (cityIndex >= 0)
                    mCityPicker.setValue(cityIndex);
            } else {
                mCityPicker.setMaxValue(0);
                mCityPicker.setMinValue(0);
                mCityPicker.setVisibility(View.INVISIBLE);
            }
            mProvincePicker.setOnValueChangedListener(new OnValueChangeListener() {

                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    final String[] cityArray = mCityManager.getCity(provinceArray[picker.getValue()]);
                    try {
                        if (cityArray != null) {
                            mCityPicker.setVisibility(View.VISIBLE);
                            mCityPicker.setDisplayedValues(null);
                            mCityPicker.setMaxValue(cityArray.length - 1);
                            mCityPicker.setMinValue(0);
                            mCityPicker.setDisplayedValues(cityArray);
                        } else {
                            mCityPicker.setVisibility(View.INVISIBLE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();// 快速滑动Picker时有时会异常，这里保护一下
                    }
                }
            });
            mSelectCityDialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.city)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mFilter.province = mCityManager.getProvinceString(mProvincePicker
                                    .getValue());
                            mFilter.city = mCityManager.getCityString(mProvincePicker.getValue(),
                                    mCityPicker.getValue());
                            StringBuilder location = new StringBuilder();
                            if (!TextUtils.isEmpty(mFilter.province)
                                    && !mFilter.province
                                            .equals(getString(R.string.filter_condition_unlimited))) {
                                location.append(mFilter.province).append(" ");
                            }
                            if (!TextUtils.isEmpty(mFilter.city)
                                    && !mFilter.city
                                            .equals(getString(R.string.filter_condition_unlimited))) {
                                location.append(mFilter.city);
                            }
                            if (!TextUtils.isEmpty(location.toString())) {
                                mCityItem.setDesText(location.toString());
                            } else {
                                mCityItem
                                        .setDesText(getString(R.string.filter_condition_unlimited));
                            }
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mSelectCityDialog.dismiss();
                        }
                    }).setView(pickerView).show();
        } else {
            mSelectCityDialog.show();
        }
    }

    private void showSelectGender() {
        if (mSelectGenderDialog == null) {
            mSelectGenderDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.gender)
                    .setSingleChoiceItems(
                            new String[] {
                                    getString(R.string.filter_condition_unlimited),
                                    getString(R.string.male), getString(R.string.female)
                            }, 0, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    switch (which) {
                                        case 0:
                                            mGenderItem
                                                    .setDesText(getString(R.string.filter_condition_unlimited));
                                            dialog.dismiss();
                                            mFilter.gender = -1;
                                            break;
                                        case 1:
                                            mGenderItem.setDesText(getString(R.string.male));
                                            dialog.dismiss();
                                            mFilter.gender = 1;
                                            break;
                                        case 2:
                                            mGenderItem.setDesText(getString(R.string.female));
                                            dialog.dismiss();
                                            mFilter.gender = 2;
                                            break;
                                    }
                                }

                            }).show();
        } else {
            mSelectGenderDialog.show();
        }
    }

    private void showSelectAuth() {
        if (mSelectAuthDialog == null) {
            mSelectAuthDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.authentication_user)
                    .setSingleChoiceItems(
                            new String[] {
                                    getString(R.string.filter_condition_unlimited),
                                    getString(R.string.yes), getString(R.string.no)
                            }, 0, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    switch (which) {
                                        case 0:
                                            mAuthItem
                                                    .setDesText(getString(R.string.filter_condition_unlimited));
                                            dialog.dismiss();
                                            mFilter.userType = -1;
                                            break;
                                        case 1:
                                            mAuthItem.setDesText(getString(R.string.yes));
                                            dialog.dismiss();
                                            mFilter.userType = 1;
                                            break;
                                        case 2:
                                            mAuthItem.setDesText(getString(R.string.no));
                                            dialog.dismiss();
                                            mFilter.userType = 0;
                                            break;
                                    }
                                }

                            }).show();
        } else {
            mSelectAuthDialog.show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mCallBack);
    }

    XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onGetSubjectList(int transactionId, java.util.List<protocol.meta.Subject> list) {
            if (transactionId == mTid) {
                if(list != null && list.size() != 0){
                    mLoadingList.onLoadingComplete(false);
                    List<GameFilterSubject> tmpList = new ArrayList<GameFilterSubject>();
                    for(Subject s : list){
                        GameFilterSubject filter = new GameFilterSubject();
                        //是否已经勾选
                        for(String name : mFilter.subjectIdList){
                            if(name.equals(s.subjectName)){
                                filter.selected = true;
                            }
                        }
                        filter.subject = s;
                        tmpList.add(filter);
                    }
                    mGameFilterList = tmpList;
                    mAdapter.addTail(tmpList);
                }else{
                    mLoadingList.onNoContent();
                }

            }
        };

        @Override
        public void onGetSubjectListError(int transactionId, int errCode, String err) {
            if (transactionId == mTid) {
                if (errCode == XoneServiceCode.NETWORK_ERR_COMMON) {
                    mLoadingList.onNoNetwork();
                } else {
                    mLoadingList.onLoadingError();
                }
            }
        };
    };

    private class GameFilterAdapter extends LinkedListAdapter<GameFilterSubject> {

        private Context mContext;

        public GameFilterAdapter(Context context) {
            mContext = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.view_game_filter_item, null);
                ViewRender render = new ViewRender(convertView);
                convertView.setTag(render);
            }
            ViewRender render = (ViewRender)convertView.getTag();
            render.render(getItem(position));
            return convertView;
        }

        class ViewRender {

            TextView gameName;
            CheckBox filterCheck;

            public ViewRender(View v) {
                gameName = (TextView)v.findViewById(R.id.game_filter_name);
                filterCheck = (CheckBox)v.findViewById(R.id.game_filter_switch);
            }

            public void render(final GameFilterSubject filter) {
                if (filter != null && filter.subject != null) {
                    gameName.setText(filter.subject.subjectName);
                    filterCheck.setChecked(filter.selected);
                    filterCheck.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            filterCheck.setChecked(filterCheck.isChecked());
                            filter.selected = filterCheck.isChecked();
                        }
                    });
                }
            }
        }

    }
}
